import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * StructuredTaskScope 实现结构化并发
 *
 * @author Junki
 * @date 2023-11-14 09:43:25
 */
public class Demo02 {

    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    Response handle() throws ExecutionException, InterruptedException {
        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
            Supplier<String> user = scope.fork(() -> findUser());
            Supplier<Integer> order = scope.fork(() -> fetchOrder());

            scope.join().throwIfFailed();

            return new Response(user.get(), order.get());
        }
    }

    private String findUser() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
//        int i = 1 / 0;
        System.out.println("findUser执行完毕");
        return "Junki";
    }

    private Integer fetchOrder() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("fetchOrder执行完毕");
        return 60060;
    }

    private record Response(String theUser, int theOrder) {
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Response response = new Demo02().handle();
        System.out.println(response);
    }
}
